using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using hao_Common.AutoMapper.Services;
using hao_Common.Http.Interfaces;
using hao_Common.Consul.Services;
using hao_Common.Response.Models;
using hao_Common.Logging.Helpers;
using hao_Dto;
using hao_Dto.User;
using hao_Model;
using hao_Model.Enums;
using hao_Reppsitory.Order;
using hao_Reppsitory.User;
using hao_Reppsitory.Product;
using hao_Reppsitory;
using User.Service.Address;
using Microsoft.Extensions.Logging;
using System.Diagnostics;

namespace Order.Service
{
    /// <summary>
    /// 订单服务实现
    /// </summary>
    public class OrderService : IOrderService
    {
        private readonly IOrderRepository _orderRepository;
        private readonly IUserRepository _userRepository;
        private readonly IAddressRepository _addressRepository;
        private readonly IProductRepository _productRepository;
        private readonly IProductImageRepository _productImageRepository;
        private readonly IMapperService _mapperService;
        private readonly IHttpHelper _httpHelper;
        private readonly IServiceDiscovery _serviceDiscovery;
        private readonly ILogger<OrderService> _logger;

        public OrderService(
            IOrderRepository orderRepository,
            IUserRepository userRepository,
            IAddressRepository addressRepository,
            IProductRepository productRepository,
            IProductImageRepository productImageRepository,
            IMapperService mapperService,
            IHttpHelper httpHelper,
            IServiceDiscovery serviceDiscovery,
            ILogger<OrderService> logger)
        {
            _orderRepository = orderRepository;
            _userRepository = userRepository;
            _addressRepository = addressRepository;
            _productRepository = productRepository;
            _productImageRepository = productImageRepository;
            _mapperService = mapperService;
            _httpHelper = httpHelper;
            _serviceDiscovery = serviceDiscovery;
            _logger = logger;
        }

        public async Task<Guid> CreateOrderAsync(CreateOrderDto dto, Guid buyerId)
        {
            var stopwatch = Stopwatch.StartNew();
            _logger.LogBusinessOperation("开始创建订单", new { BuyerId = buyerId, ProductId = dto.ProductId, FinalPrice = dto.FinalPrice });
            
            // 通过服务发现获取用户服务地址，验证买家是否存在
            var userServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-user-api");
            if (string.IsNullOrEmpty(userServiceUrl))
            {
                _logger.LogError("User service not available");
                throw new InvalidOperationException("用户服务暂不可用，请稍后重试");
            }

            // 调用用户服务内部接口验证买家信息
            var buyerUrl = $"{userServiceUrl}/api/internal/user/{buyerId}";
            var userCallStopwatch = Stopwatch.StartNew();
            var buyerResponse = await _httpHelper.GetAsync<ApiResponse<UserDto>>(buyerUrl);
            userCallStopwatch.Stop();
            
            _logger.LogMicroserviceCall("hao-order-api", "hao-user-api", "验证买家信息", 
                buyerResponse?.Success == true, userCallStopwatch.ElapsedMilliseconds, new { BuyerId = buyerId });
            
            if (buyerResponse?.Success != true || buyerResponse.Data == null)
            {
                _logger.LogWarning("Buyer validation failed: {BuyerId}, Code: {Code}, Message: {Message}", 
                    buyerId, buyerResponse?.Code, buyerResponse?.Message);
                throw new ArgumentException("买家用户不存在或已被禁用");
            }

            // 通过服务发现获取商品服务地址
            var productServiceUrl = await _serviceDiscovery.GetServiceUrlAsync("hao-product-api");
            if (string.IsNullOrEmpty(productServiceUrl))
            {
                _logger.LogError("Product service not available");
                throw new InvalidOperationException("商品服务暂不可用，请稍后重试");
            }

            // 调用商品服务内部接口验证商品信息
            var productUrl = $"{productServiceUrl}/api/internal/product/{dto.ProductId}";
            var productCallStopwatch = Stopwatch.StartNew();
            var productResponse = await _httpHelper.GetAsync<ApiResponse<ProductResponseDto>>(productUrl);
            productCallStopwatch.Stop();
            
            _logger.LogMicroserviceCall("hao-order-api", "hao-product-api", "验证商品信息", 
                productResponse?.Success == true, productCallStopwatch.ElapsedMilliseconds, new { ProductId = dto.ProductId });
            
            if (productResponse?.Success != true || productResponse.Data == null)
            {
                _logger.LogWarning("Product API failed: {ProductId}, Code: {Code}, Message: {Message}", 
                    dto.ProductId, productResponse?.Code, productResponse?.Message);
                throw new ArgumentException(productResponse?.Message ?? "商品不存在或已下架");
            }

            var product = productResponse.Data;

            // 验证买家不能购买自己的商品
            if (product.UserId == buyerId)
                throw new ArgumentException("不能购买自己发布的商品");

            // 验证地址（如果是邮寄方式）
            if (dto.DeliveryMethod == DeliveryMethod.Mail && dto.BuyerAddressId.HasValue)
            {
                var address = await _addressRepository.GetByIdAsync(dto.BuyerAddressId.Value);
                if (address == null || address.UserId != buyerId)
                    throw new ArgumentException("收货地址无效");
            }

            // 生成订单号
            var orderNumber = await _orderRepository.GenerateOrderNumberAsync();

            // 创建订单
            var order = new hao_Model.Order
            {
                Id = Guid.NewGuid(),
                OrderNumber = orderNumber,
                BuyerId = buyerId,
                SellerId = product.UserId,
                ProductId = dto.ProductId,
                ProductTitle = product.Title ?? "未知商品",
                ProductPrice = product.Price,
                FinalPrice = dto.FinalPrice,
                Quantity = dto.Quantity,
                TotalAmount = dto.FinalPrice * dto.Quantity,
                DeliveryMethod = dto.DeliveryMethod,
                Status = OrderStatus.PendingSellerConfirm,
                PaymentStatus = PaymentStatus.Unpaid,
                DeliveryStatus = DeliveryStatus.PendingShipment,
                BuyerAddressId = dto.BuyerAddressId,
                BuyerMessage = dto.BuyerMessage,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            var orderId = await _orderRepository.AddAsync(order);
            
            stopwatch.Stop();
            _logger.LogPerformance("创建订单完成", stopwatch.ElapsedMilliseconds, 
                new { OrderId = orderId, BuyerId = buyerId, ProductId = dto.ProductId });
            
            return orderId;
        }

        public async Task<OrderResponseDto> GetOrderByIdAsync(Guid orderId)
        {
            var order = await _orderRepository.GetByIdAsync(orderId);
            if (order == null)
                return null;

            return await MapToOrderResponseDto(order);
        }

        public async Task<OrderResponseDto> GetOrderByNumberAsync(string orderNumber)
        {
            var order = await _orderRepository.GetByOrderNumberAsync(orderNumber);
            if (order == null)
                return null;

            return await MapToOrderResponseDto(order);
        }

        public async Task<bool> UpdateOrderAsync(Guid orderId, CreateOrderDto dto)
        {
            var order = await _orderRepository.GetByIdAsync(orderId);
            if (order == null)
                return false;

            // 只有待卖家确认状态的订单才能修改
            if (order.Status != OrderStatus.PendingSellerConfirm)
                throw new InvalidOperationException("订单状态不允许修改");

            order.FinalPrice = dto.FinalPrice;
            order.Quantity = dto.Quantity;
            order.TotalAmount = dto.FinalPrice * dto.Quantity;
            order.DeliveryMethod = dto.DeliveryMethod;
            order.BuyerAddressId = dto.BuyerAddressId;
            order.BuyerMessage = dto.BuyerMessage;
            order.UpdatedAt = DateTime.UtcNow;

            return await _orderRepository.UpdateAsync(order);
        }

        public async Task<bool> CancelOrderAsync(Guid orderId, string reason, Guid operatorId)
        {
            if (!await _orderRepository.CanCancelOrderAsync(orderId))
                throw new InvalidOperationException("订单状态不允许取消");

            var order = await _orderRepository.GetByIdAsync(orderId);
            if (order == null)
                return false;

            order.Status = OrderStatus.Cancelled;
            order.CancelReason = reason;
            order.CancelledAt = DateTime.UtcNow;
            order.UpdatedAt = DateTime.UtcNow;

            await _orderRepository.UpdateAsync(order);
            await _orderRepository.UpdateOrderStatusAsync(orderId, OrderStatus.Cancelled, operatorId, reason);

            return true;
        }

        public async Task<(List<OrderListDto> orders, int total)> GetOrdersAsync(OrderSearchDto searchDto)
        {
            var (orders, total) = await _orderRepository.SearchOrdersAsync(searchDto);
            var orderDtos = new List<OrderListDto>();

            foreach (var order in orders)
            {
                var dto = _mapperService.Map<OrderListDto>(order);
                dto.StatusName = order.Status.GetDescription();
                dto.PaymentStatusName = order.PaymentStatus.GetDescription();
                
                // 获取买家和卖家姓名
                var buyer = await _userRepository.GetByIdAsync(order.BuyerId);
                var seller = await _userRepository.GetByIdAsync(order.SellerId);
                dto.BuyerName = buyer?.UserName ?? "未知用户";
                dto.SellerName = seller?.UserName ?? "未知用户";
                
                orderDtos.Add(dto);
            }

            return (orderDtos, total);
        }

        public async Task<List<OrderListDto>> GetBuyerOrdersAsync(Guid buyerId, OrderStatus? status = null)
        {
            var orders = await _orderRepository.GetBuyerOrdersAsync(buyerId, status);
            var orderDtos = new List<OrderListDto>();

            foreach (var order in orders)
            {
                var dto = _mapperService.Map<OrderListDto>(order);
                dto.StatusName = order.Status.GetDescription();
                dto.PaymentStatusName = order.PaymentStatus.GetDescription();
                
                var seller = await _userRepository.GetByIdAsync(order.SellerId);
                dto.SellerName = seller?.UserName ?? "未知用户";
                
                // 获取商品第一张图片
                var productImages = await _productImageRepository.GetAllAsync();
                var firstImage = productImages?.FirstOrDefault(img => img.ProductId == order.ProductId && !img.IsDeleted);
                dto.ProductImage = firstImage?.Url;
                
                orderDtos.Add(dto);
            }

            return orderDtos;
        }

        public async Task<List<OrderListDto>> GetSellerOrdersAsync(Guid sellerId, OrderStatus? status = null)
        {
            var orders = await _orderRepository.GetSellerOrdersAsync(sellerId, status);
            var orderDtos = new List<OrderListDto>();

            foreach (var order in orders)
            {
                var dto = _mapperService.Map<OrderListDto>(order);
                dto.StatusName = order.Status.GetDescription();
                dto.PaymentStatusName = order.PaymentStatus.GetDescription();
                
                var buyer = await _userRepository.GetByIdAsync(order.BuyerId);
                dto.BuyerName = buyer?.UserName ?? "未知用户";
                
                // 获取商品第一张图片
                var productImages = await _productImageRepository.GetAllAsync();
                var firstImage = productImages?.FirstOrDefault(img => img.ProductId == order.ProductId && !img.IsDeleted);
                dto.ProductImage = firstImage?.Url;
                
                orderDtos.Add(dto);
            }

            return orderDtos;
        }

        public async Task<bool> SellerConfirmOrderAsync(Guid orderId, Guid sellerId, string sellerMessage = null)
        {
            var order = await _orderRepository.GetByIdAsync(orderId);
            if (order == null)
                return false;

            // 验证订单状态
            if (order.Status != OrderStatus.PendingSellerConfirm)
                throw new InvalidOperationException("订单状态不允许确认");

            // 验证卖家权限
            if (order.SellerId != sellerId)
                throw new InvalidOperationException("无权操作此订单");

            order.Status = OrderStatus.PendingDelivery;
            order.SellerMessage = sellerMessage;
            order.UpdatedAt = DateTime.UtcNow;

            await _orderRepository.UpdateAsync(order);
            await _orderRepository.UpdateOrderStatusAsync(orderId, OrderStatus.PendingDelivery, sellerId, "卖家确认订单");

            return true;
        }

        public async Task<bool> ConfirmReceiptAsync(Guid orderId, Guid buyerId)
        {
            if (!await _orderRepository.CanConfirmOrderAsync(orderId))
                throw new InvalidOperationException("订单状态不允许确认收货");

            var order = await _orderRepository.GetByIdAsync(orderId);
            if (order == null || order.BuyerId != buyerId)
                return false;

            order.Status = OrderStatus.Completed;
            order.CompletedAt = DateTime.UtcNow;
            order.UpdatedAt = DateTime.UtcNow;

            await _orderRepository.UpdateAsync(order);
            await _orderRepository.UpdateOrderStatusAsync(orderId, OrderStatus.Completed, buyerId, "买家确认收货");

            return true;
        }

        public async Task<bool> CompleteOrderAsync(Guid orderId)
        {
            var order = await _orderRepository.GetByIdAsync(orderId);
            if (order == null || order.Status != OrderStatus.PendingDelivery)
                return false;

            order.Status = OrderStatus.Completed;
            order.CompletedAt = DateTime.UtcNow;
            order.UpdatedAt = DateTime.UtcNow;

            await _orderRepository.UpdateAsync(order);
            await _orderRepository.UpdateOrderStatusAsync(orderId, OrderStatus.Completed, null, "订单自动完成");

            return true;
        }

        public async Task<TrackingInfoDto> GetTrackingInfoAsync(string trackingNumber)
        {
            // 这里应该调用第三方物流API获取物流信息
            // 暂时返回模拟数据
            return new TrackingInfoDto
            {
                TrackingNumber = trackingNumber,
                CourierCompany = "顺丰速运",
                Status = DeliveryStatus.InTransit,
                StatusDescription = "运输中",
                Events = new List<TrackingEventDto>
                {
                    new TrackingEventDto
                    {
                        Time = DateTime.Now.AddHours(-2),
                        Location = "北京分拣中心",
                        Description = "快件已到达北京分拣中心"
                    },
                    new TrackingEventDto
                    {
                        Time = DateTime.Now.AddHours(-4),
                        Location = "上海转运中心",
                        Description = "快件已从上海转运中心发出"
                    }
                },
                EstimatedDelivery = DateTime.Now.AddDays(1)
            };
        }

        public async Task<bool> UpdateDeliveryStatusAsync(Guid orderId, DeliveryStatus status)
        {
            return await _orderRepository.UpdateDeliveryStatusAsync(orderId, status);
        }

        public async Task<OrderStatisticsDto> GetOrderStatisticsAsync(Guid? userId = null)
        {
            return await _orderRepository.GetOrderStatisticsAsync(userId);
        }

        public async Task<List<OrderDailyStatsDto>> GetDailyOrderStatsAsync(DateTime startDate, DateTime endDate, Guid? userId = null)
        {
            return await _orderRepository.GetDailyOrderStatsAsync(startDate, endDate, userId);
        }

        public async Task<bool> ValidateOrderOwnershipAsync(Guid orderId, Guid userId)
        {
            return await _orderRepository.CheckOrderOwnershipAsync(orderId, userId);
        }

        public async Task<bool> CanCancelOrderAsync(Guid orderId)
        {
            return await _orderRepository.CanCancelOrderAsync(orderId);
        }

        public async Task<bool> ValidateSellerOwnershipAsync(Guid orderId, Guid sellerId)
        {
            var order = await _orderRepository.GetByIdAsync(orderId);
            return order != null && order.SellerId == sellerId;
        }

        public async Task<bool> CanConfirmOrderAsync(Guid orderId)
        {
            var order = await _orderRepository.GetByIdAsync(orderId);
            return order != null && order.Status == OrderStatus.PendingDelivery;
        }

        private async Task<OrderResponseDto> MapToOrderResponseDto(hao_Model.Order order)
        {
            var dto = _mapperService.Map<OrderResponseDto>(order);
            
            // 获取枚举描述
            dto.DeliveryMethodName = order.DeliveryMethod.GetDescription();
            dto.StatusName = order.Status.GetDescription();
            
            // 获取买家和卖家信息
            var buyer = await _userRepository.GetByIdAsync(order.BuyerId);
            var seller = await _userRepository.GetByIdAsync(order.SellerId);
            dto.BuyerName = buyer?.UserName ?? "未知用户";
            dto.SellerName = seller?.UserName ?? "未知用户";
            
            // 获取收货地址信息
            if (order.BuyerAddressId.HasValue)
            {
                var address = await _addressRepository.GetByIdAsync(order.BuyerAddressId.Value);
                if (address != null)
                {
                    dto.BuyerAddress = _mapperService.Map<AddressDto>(address);
                }
            }
            
            return dto;
        }
    }
}